﻿using PioneerBoilerplate.Model.Admin;
using PioneerBoilerplate.Repository;
using PioneerBoilerplate.Service.Admin.Dictionary;
using PioneerBoilerplate.Service.Admin.Dictionary.Input;
using PioneerBoilerplate.Service.Admin.Dictionary.Output;
using PioneerBoilerplate.Service.Base;
using PioneerBoilerplate.Util;
using PioneerBoilerplate.Util.Input;
using PioneerBoilerplate.Util.Output;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using PioneerBoilerplate.Repository.UnitOfWorks;
using System.Collections.Generic;
using PioneerBoilerplate.Repository.Repositories;

namespace Admin.Core.Service.Admin.Dictionary
{
    public class DictionaryService : BaseService, IDictionaryService
    {
        private readonly IDictionaryRepository _dictionaryRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;

        public DictionaryService(
            IDictionaryRepository dictionaryRepository,
            IUnitOfWorkManager unitOfWorkManager)
        {
            _dictionaryRepository = dictionaryRepository;
            _unitOfWorkManager = unitOfWorkManager;
        }

        public async Task<IResponseOutput> GetAsync(long id)
        {
            var result = Mapper.Map<DictionaryGetOutput>(await _dictionaryRepository.FirstOrDefaultAsync(a => a.Id == id));
            return ResponseOutput.Ok(result);
        }

        public async Task<IResponseOutput> PageAsync(PageInput<DictionaryEntity> input)
        {
            var key = input.Filter?.Name;
            var dictionaryTypeId = input.Filter?.DictionaryTypeId;

            PaginationSpecification<DictionaryEntity> specification = new();
            specification.WhereIf(key.NotNull(), e => e.Name.Contains(key));
            specification.WhereIf(dictionaryTypeId.HasValue && dictionaryTypeId.Value > 0, e => e.DictionaryTypeId == dictionaryTypeId);
            specification.OrderBy = q => q.OrderByDescending(e => e.Id);
            specification.PageIndex = input.CurrentPage;
            specification.PageSize = input.PageSize;

            var list = await _dictionaryRepository.GetListAsync(specification);
            var data = new PageOutput<DictionaryListOutput>()
            {
                List = Mapper.Map<List<DictionaryListOutput>>(list.Items),
                Total = list.TotalItems
            };

            return ResponseOutput.Ok(data);
        }

        public async Task<IResponseOutput> AddAsync(DictionaryAddInput input)
        {
            var dictionary = Mapper.Map<DictionaryEntity>(input);
            var id = (await _dictionaryRepository.InsertAsync(dictionary)).Id;
            return ResponseOutput.Result(id > 0);
        }

        public async Task<IResponseOutput> UpdateAsync(DictionaryUpdateInput input)
        {
            if (!(input?.Id > 0))
            {
                return ResponseOutput.NotOk();
            }

            var entity = await _dictionaryRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
            if (!(entity?.Id > 0))
            {
                return ResponseOutput.NotOk("数据字典不存在！");
            }

            Mapper.Map(input, entity);
            await _dictionaryRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }

        public async Task<IResponseOutput> DeleteAsync(long id)
        {
            var result = true;
            if (id > 0)
            {
                var entity = await _dictionaryRepository.FirstOrDefaultAsync(a => a.Id == id);
                if (entity == null)
                    result = false;

                await _dictionaryRepository.DeleteAsync(entity);
            }
            return ResponseOutput.Result(result);
        }

        public async Task<IResponseOutput> SoftDeleteAsync(long id)
        {
            var result = false;
            var entity = await _dictionaryRepository.FirstOrDefaultAsync(a => a.Id == id);
            if (entity != null) 
            {
                entity.IsDeleted = true;
                result = await _dictionaryRepository.UpdateAsync(entity) != null;
            }

            return ResponseOutput.Result(result);
        }

        public async Task<IResponseOutput> BatchSoftDeleteAsync(long[] ids)
        {         
            using (var uowHandle = _unitOfWorkManager.Begin<ApplicationDbContext>())
            {
                var entitys = await _dictionaryRepository.GetAll().Where(a => ids.Contains(a.Id)).ToListAsync();

                entitys.ForEach(async entity => 
                { 
                    entity.IsDeleted = true;
                    await _dictionaryRepository.UpdateAsync(entity);
                });
                uowHandle.SaveChange();
            }
            return ResponseOutput.Ok();
        }
    }
}